package api

import (
	"codetest/apps/model"
	"codetest/library/response"

	"github.com/gogf/gf/net/ghttp"
	"gorm.io/gorm"
)

type Controller struct {
	db *gorm.DB
}

func NewController(db *gorm.DB) *Controller {
	return &Controller{
		db,
	}
}

// GetIp 获取IP地址
func (c *Controller) GetIp(r *ghttp.Request) {
	var devs []model.DevInfo
	result := c.db.Find(&devs)
	if result.Error != nil {
		panic("error query db")
	}

	var ips []string
	for _, val := range devs {
		ips = append(ips, val.Ip+":"+val.Name)
	}
	response.JSON(r, 0, "ok", ips)
}

func (c *Controller) UpdateIp(r *ghttp.Request) {
	uid := r.Get("uid").(string)
	ip := r.Get("ip").(string)
	name := r.Get("name").(string)

	if len(uid) < 4 {
		r.Response.Write("uid less 4")
	}

	devInfo := &model.DevInfo{Uid: uid, Ip: ip, Name: name}
	result := c.db.Where("uid=?", uid).First(devInfo)
	if result.RowsAffected == 0 {
		c.db.Create(devInfo)
	}

	c.db.Model(devInfo).Updates(devInfo)
	r.Response.Write("ok")
}
